package com.yellowpage.white.generator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public abstract class AberstractGenerator implements Generator{
	VelocityEngine velocityEngine;
	VelocityContext velocityContext;
	
	protected Map properties = null;	
	
	protected List<Map> fieldList = new ArrayList();
	
	public AberstractGenerator() {
		velocityEngine = new VelocityEngine();
		velocityContext = new VelocityContext();

		velocityEngine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);

		try {
			velocityEngine.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 需实现的方法
	 */
	public abstract void generate();
	
	//传入参数的方法
	public void setProperties(Map properties){
		this.properties = properties;
	}

	public void generate(File templateFile, File javaFile) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(javaFile));
			BufferedReader reader = new BufferedReader(new FileReader(
					templateFile));

			StringBuffer content = new StringBuffer();
			char[] c = new char[1];
			try {
				while (reader.read(c, 0, 1) == 1) {
					content.append(c[0]);
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			} finally {
				try {
					reader.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}

			velocityEngine.evaluate(velocityContext, writer, "", content
					.toString());

			reader.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ResourceNotFoundException rnfe) {
			// couldn't find the template
			rnfe.printStackTrace();
		} catch (ParseErrorException pee) {
			// syntax error : problem parsing the template
			pee.printStackTrace();
		} catch (MethodInvocationException mie) {
			// something invoked in the template
			// threw an exception
			mie.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setObject(String key, Object obj) {
		velocityContext.put(key, obj);
	}
	
	public Object getObject(String key) {
		return velocityContext.get(key);
		
	}
	
	public String getPackageFilePath(String srcPath, String packageName){
		return srcPath + packageName.replaceAll("\\.", "\\\\") + "\\";
	}	
	
}
